import Dialog from '../../vant-weapp/dialog/dialog';
import Toast from '../../vant-weapp/toast/toast';
import fw from '../../core/framework.js'
const _app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    deviceData: [],
    keywords: '',
    paging: {
      index: 0,
      size: 20,
      totalPages: 0,
      totalElements: 0
    },
    _paging: {
      index: 0,
      size: 20,
      totalPages: 0,
      totalElements: 0
    },
    showpopup: false,
    searchTimer: null,
    searchStatus: 0,
    isLogin: false,
    pageBottom: _app.BOTTOM_DISTANCE || 10,
    btnsShow: false,
    btnsActions: [
      {
        name: '编辑',
        value: 'edit'
      },
      {
        name: '删除',
        value: 'delete'
      }
    ],
    currDevice: null,
    baseURL:fw.url.getBaseScreenShotsURL()
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var self = this;
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  onShow: function () {
    let self = this;
    this.setData({
      isLogin: fw.user.islogin(),
      paging: fw.clone(this.data._paging)
    });
    if (this.data.isLogin) {
      self.getDeviceListData();
      fw.setUntreatedAlarmEvent();
    }
  },
  search: function (event) {
    let self = this;
    if (!this.data.isLogin) return false;
    clearTimeout(self.data.searchTimer);
    self.setData({
      searchTimer: (setTimeout(function () {
        self.setData({
          keywords: event.detail,
          paging: fw.clone(self.data._paging)
        });
        self.getDeviceListData((event.detail || "").length > 0 ? 'search' : null);
      }, 100))
    })
  },
  getDeviceListData: function (searchStaus, isPaging) {
    let self = this;
    let _data = self.data;
    let _paging = _data.paging;
    let ajaxOpts = {
      index: _paging.index,
      size: _paging.size,
      name: _data.keywords || ''
    };
    var setSearchStatus = function () {
      self.setData({
        searchStatus: searchStaus == 'search' ? 1 : 2
      });
    };
    fw.ajax('device/search', ajaxOpts).then(res => {
      if (res.code == 0) {
        _paging.totalElements = res.data.totalElements;
        self.setData({
          // deviceData:[ ...res.data.content, ...res.data.content, ...res.data.content, ...res.data.content],
          deviceData: self.toUIData(res.data.content,isPaging),
          paging: _paging,
          searchStatus: 0
        });
        if (res.data.content.length == 0) {
          setSearchStatus();
        }
      } else {
        setSearchStatus();
      }
    });
  },
  toUIData(data, isPaging) {
    let self = this;
    let uiData = [];
    let _data = self.data.deviceData;
    let _len = _data.length;
    let len = data.length;
    if (_len > 0 && isPaging) {
      uiData = fw.clone(_data);
    }
    data.forEach((item, index) => {
       item.bgUrl = item.bg_url ? (self.data.baseURL+item.bg_url):'';
       uiData.push(item);
    });
    return uiData;
  },
  goLivePlayer() {
    let roomId = [2] // 填写具体的房间号，可通过下面【获取直播房间列表】 API 获取
    let customParams = encodeURIComponent(JSON.stringify({
      path: 'pages/index/index',
      pid: 1
    })) // 开发者在直播间页面路径上携带自定义参数（如示例中的path和pid参数），后续可以在分享卡片链接和跳转至商详页时获取，详见【获取自定义参数】、【直播间到商详页面携带参数】章节（上限600个字符，超过部分会被截断）
    wx.navigateTo({
      url: `plugin-private://wx2b03c6e691cd7370/pages/live-player-plugin?room_id=${roomId}&custom_params=${customParams}`
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    if (!this.data.isLogin) return false;
    this.setData({
      ['paging.index']: 0
    });
    this.getDeviceListData();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var _paging = this.data.paging;
    if (_paging.totalElements != 0 && ((_paging.index + 1) * _paging.size > _paging.totalElements)) {
      return false;
    }
    this.setData({
      ['paging.index']: (_paging.index + 1)
    });
    this.getDeviceListData('search', true);
  },
  getPhoneNumber(e) {
    fw.url.goLogin(e);
  },
  goDeviceDetail(e) {
    var data = fw.getTargetData(e, 'device');
    fw.url.go('device_detail', { device: data });
  },
  gotoCreateNewDevice(){
    fw.url.go('device_edit',{type:'create'});
  },
  openBtns(e) {
    var data = fw.getTargetData(e, 'device');
    this.setData({
      btnsShow: true,
      currDevice: data
    })
  },
  closeBtnsShow(e) {
    this.setData({
      btnsShow: false
    })
  },
  chooseBtns(e) {
    var self = this;
    // var data = fw.getTargetData(e,'device');
    var currDevice = self.data.currDevice;
    switch (e.detail.value) {
      case 'edit':
        fw.url.go('device_edit',{type:'edit',device:currDevice});
        break;
      case 'delete':
        Dialog.confirm({
          title: '提示',
          message: '确认删除设备'+currDevice.name+'?',
        }).then(() => {
            fw.ajax('device/delete',{id:currDevice.id}).then(res=>{
              self.closeBtnsShow();
              self.onShow();
            })
        }).catch(() => {
           self.closeBtnsShow();
        });
        break;
      default:
        break;
    }
  }
})